import React, { useEffect, useState, useRef } from 'react';
import { Radio } from 'antd';
import { Input, Button, Toast } from 'antd-mobile';
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons';
import axios from 'axios';
import './login.css'
import SliderCaptcha from 'rc-slider-captcha';
import { getCaptcha, verifyCaptcha } from './service.js';
import { useNavigate } from 'react-router-dom';

const Login = () => {
  let nav=useNavigate()
  const [accessToken, setAccessToken] = useState(localStorage.getItem('accessToken') || '');
  const [refreshToken, setRefreshToken] = useState(localStorage.getItem('refreshToken') || '');
  const [protectedData, setProtectedData] = useState('');
  const [loginMethod, setLoginMethod] = useState('password');// 登录方式
  const [registerMethod, setRegisterMethod] = useState('username');// 注册方式

  const [username, setUsername] = useState('');// 用户名
  const [password, setPassword] = useState('');// 密码

  const [phoneNumber, setPhoneNumber] = useState('');// 手机号
  const [code, setCode] = useState('');// 验证码
  const [receivedCode, setReceivedCode] = useState('');// 收到的验证码
  const [time, setTime] = useState(0);// 倒计时
  const [isCaptcha, setisCaptcha] = useState(false)// 是否开启滑块验证码

  const videoRef = useRef(null);// 视频流
  const canvasRef = useRef(null);//  canvas
  const [isCameraOn, setIsCameraOn] = useState(false);// 是否开启摄像头
  const [isCapturing, setIsCapturing] = useState(false);// 是否正在拍照
  const [faceImage, setFaceImage] = useState('');// 人脸照片
  const [passwordVisible, setPasswordVisible] = useState(false);// 密码是否可见
  const [showRegisterForm, setShowRegisterForm] = useState(false);// 是否显示注册表单
  const [showLoginSection, setShowLoginSection] = useState(true);// 是否显示登录部分
  const getCodeFromServer = async () => {
    if (!phoneNumber) {
      Toast.show({
        content: '手机号不能为空',
      });
      return;
    }
    try {
      const response = await axios.post('http://localhost:3000/login/send-sms', { phoneNumber });
      setReceivedCode(response.data.code);
      Toast.show({
        content: '验证码已发送',
      });
      setTime(60);
      console.log("验证码为：" + response.data.code);

    } catch (error) {
      Toast.show({
        icon: 'fail',
        content: '发送验证码失败',
      });
    }
  };

  const handlePasswordLogin = async () => {
    if (!username || !password) {
      Toast.show({
        content: '用户名或密码不能为空',
      });
      return;
    }
    try {
      const response = await axios.post('http://localhost:3000/login/login', {
        username,
        password,
      });
      if (response.data.code === 200) {
        Toast.show({
          content: '登录成功',
        });
        const { accessToken, refreshToken,userid } = response.data;
        setAccessToken(accessToken);
        setRefreshToken(refreshToken);
        localStorage.setItem('accessToken', accessToken);
        localStorage.setItem('refreshToken', refreshToken);
        localStorage.setItem('registerInfo', JSON.stringify({ username, password, phoneNumber, faceImage }));
        sessionStorage.setItem('username', username);
        sessionStorage.setItem('userid',userid );
        // 跳转到主页
        //window.location.href = '/board';

        nav('/board')
      } else {
        Toast.show({
          content: '用户名或密码输入有误',
        });
      }
    } catch (error) {
      Toast.show({
        content: '登录请求失败',
      });
    }
  };

  const handleCodeLogin = async () => {
    if (code !== receivedCode) {
      Toast.show({
        content: '输入的验证码有误，请重新输入',
      });
      return;
    }
    if (!phoneNumber) {
      Toast.show({
        content: '请输入手机号',
      });
      return;
    }
    if (!isCaptcha) {
      Toast.show({
        content: '请先通过验证',
      });
      return;
    }
    try {
      const response = await axios.post('http://localhost:3000/login/telpLogin', { phoneNumber });
      if (response.data.code === 200) {
        Toast.show({
          content: '手机号登录成功',
        });
        localStorage.setItem('token', response.data.token);
        localStorage.setItem('registerInfo', JSON.stringify({ username, password, phoneNumber, faceImage }));
        sessionStorage.setItem('username', username);
        // 跳转到主页
        //window.location.href = '/board';
        nav('/board',{state:{username:username}})
      } else {-
        Toast.show({
          content: '登录失败',
        });
      }
    } catch (error) {
      Toast.show({
        content: '登录请求失败',
      });
    }
  };

  const handleFaceLogin = async () => {
    if (!faceImage) {
      Toast.show({
        content: '请先进行人脸识别',
      });
      return;
    }
    try {
      const response = await axios.post('http://localhost:3000/login/faceLogin', { faceImage });
      if (response.data.code === 200) {
        Toast.show({
          content: '人脸识别登录成功',
        });
        localStorage.setItem('accessToken', response.data.accessToken);
        localStorage.setItem('refreshToken', response.data.refreshToken);
        localStorage.setItem('registerInfo', JSON.stringify({ username, password, phoneNumber, faceImage }));
        sessionStorage.setItem('username', username);
        // 跳转到主页
      //  window.location.href = '/board';
      nav('/board',{state:{username:username}})
      } else {
        Toast.show({
          content: '人脸识别登录失败',
        });
      }
    } catch (error) {
      Toast.show({
        content: '登录请求失败',
      });
    }
  };


  //注册接口
  const handleRegister = async () => {
    if (username === '' || password === '') {
      Toast.show({
        content: '用户名和密码不能为空',
      });
      return;
    }
    if (phoneNumber === '') {
      Toast.show({
        content: '手机号和验证码不能为空',
      });
      return;
    }
    if (!faceImage) {
      Toast.show({
        content: '请先进行人脸识别',
      });
      return;
    }
    try {
      const response = await axios.post('http://localhost:3000/login/register', {
        username,
        password,
        faceImage,
        phoneNumber,
      });
      if (response.data.code === 200) {
        Toast.show({
          content: '注册成功',
        });
        setShowRegisterForm(false);
        setShowLoginSection(true);
        alert('注册成功');
        window.location.reload()
      } else {
        Toast.show({
          content: response.data.message,
        });
      }
    } catch (error) {
      Toast.show({
        content: '注册请求失败',
      });
    }
  };

  useEffect(() => {
    if (time > 0) {
      const timer = setInterval(() => {
        setTime(time - 1);
      }, 1000);
      return () => clearInterval(timer);
    }
  }, [time]);

  useEffect(() => {
    if (isCameraOn) {
      navigator.mediaDevices.getUserMedia({ video: true })
        .then(stream => {
          const video = videoRef.current;
          video.srcObject = stream;
          video.play();
        })
        .catch(error => {
          console.error('Error accessing camera:', error);
          Toast.show({
            content: '无法访问摄像头',
          });
        });
    }
    return () => {
      if (videoRef.current && videoRef.current.srcObject) {
        const stream = videoRef.current.srcObject;
        const tracks = stream.getTracks();
        tracks.forEach(track => track.stop());
      }
    };
  }, [isCameraOn]);

  const captureImage = () => {
    setIsCapturing(true);
    const video = videoRef.current;
    const canvas = canvasRef.current;
    if (!video || !canvas) {
      Toast.show({
        content: '摄像头或画布未准备好，无法捕捉图像',
      });
      setIsCapturing(false);
      return;
    }
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
    const imageData = canvas.toDataURL('image/jpeg');
    const base64Image = imageData.split(',')[1];
    if (base64Image) {
      setFaceImage(base64Image);
      Toast.show({
        content: '人脸图像已捕捉',
      });
    } else {
      Toast.show({
        content: '图像转换为 Base64 格式失败',
      });
    }
    setIsCapturing(false);
    if (video.srcObject) {
      const stream = video.srcObject;
      const tracks = stream.getTracks();
      tracks.forEach(track => track.stop());
      setIsCameraOn(false);
    }
  };


  const refreshAccessToken = async () => {
    try {
      const response = await axios.post(`http://localhost:3000/login/refresh`, {
        refreshToken
      });
      return response.data.accessToken;
    } catch (error) {
      console.error('Error refreshing token:', error);
      // 刷新失败，清除本地存储并提示重新登录
      localStorage.removeItem('accessToken');
      localStorage.removeItem('refreshToken');
      setAccessToken('');
      setRefreshToken('');
      return null;
    }
  };

  useEffect(() => {
    if (!accessToken && localStorage.getItem('accessToken')) {
      setAccessToken(localStorage.getItem('accessToken'));
    }
    if (!refreshToken && localStorage.getItem('refreshToken')) {
      setRefreshToken(localStorage.getItem('refreshToken'));
    }
  }, []);

  return (
    <div className='main'>
      <div className="login-container">
        {showLoginSection && (
          //... 登录表单部分 ...
          <div>
            <h1 className="login-title">登录到Maijia!</h1>
            <div className="login-methods">
              <div
                className={`login-method-button ${loginMethod === 'password' ? 'active' : ''}`}
                onClick={() => setLoginMethod('password')}
              >
                用户名密码
              </div>
              <div
                className={`login-method-button ${loginMethod === 'code' ? 'active' : ''}`}
                onClick={() => setLoginMethod('code')}
              >
                短信验证
              </div>
              <div
                className={`login-method-button ${loginMethod === 'face' ? 'active' : ''}`}
                onClick={() => setLoginMethod('face')}
              >
                人脸识别
              </div>
            </div>
            {/* 用户名密码登录 */}
            {loginMethod === 'password' && (
              <div className="login-form">
                <Input
                  placeholder="用户名"
                  value={username}
                  onChange={(e) => setUsername(e)}
                  className="login-input"
                />
                <div className="password-input-container">
                  <Input
                    placeholder="密码"
                    type={passwordVisible ? 'text' : 'password'}
                    value={password}
                    onChange={(e) => setPassword(e)}
                    className="login-input"
                  />
                  <div className="password-eye-icon">
                    {passwordVisible ? (
                      <EyeOutline onClick={() => setPasswordVisible(false)} className="text-gray-500 cursor-pointer" />
                    ) : (
                      <EyeInvisibleOutline onClick={() => setPasswordVisible(true)} className="text-gray-500 cursor-pointer" />
                    )}
                  </div>
                </div>
                <div>
                  <Button onClick={handlePasswordLogin} className="login-button">
                    登录
                  </Button>
                </div>

                <Button onClick={() => {
                  setShowRegisterForm(true);
                  setShowLoginSection(false);
                }} className="register-button">
                  注册
                </Button>
              </div>
            )}
            {/* 短信验证码登录 */}
            {loginMethod === 'code' && (
              <div className="login-form">
                <Input
                  placeholder="手机号"
                  value={phoneNumber}
                  onChange={(e) => setPhoneNumber(e)}
                  className="login-input"
                />
                <div className="code-input-container">
                  <Input
                    placeholder="验证码"
                    value={code}
                    onChange={(e) => setCode(e)}
                    className="login-input2"
                  />
                  <Button
                    onClick={getCodeFromServer}
                    className={`code-button ${time > 0 ? 'disabled' : ''}`}
                    disabled={time > 0}
                  >
                    {time > 0 ? `${time} 秒后重试` : '发送验证码'}
                  </Button>
                </div>
                <div>
                  <>
                    <SliderCaptcha
                      mode="float"
                      request={getCaptcha}
                      onVerify={(data) => {
                        console.log(data.x > 85 && data.x < 95);
                        setisCaptcha(data.x > 85 && data.x < 95);
                        return verifyCaptcha(data);
                      }}
                    />
                    <br />

                  </>
                </div>
                <div>
                  <Button onClick={handleCodeLogin} className="login-button">
                    登录
                  </Button>
                </div>

                <Button onClick={() => {
                  setShowRegisterForm(true);
                  setShowLoginSection(false);
                }} className="register-button">
                  注册
                </Button>
              </div>
            )}
            {/* 人脸识别登录 */}
            {loginMethod === 'face' && (
              <div className="login-form">
                <div>
                  {!isCameraOn && (
                    <Button onClick={() => setIsCameraOn(true)} className="open-camera-button">
                      打开摄像头
                    </Button>
                  )}
                </div>
                <div>
                  {isCameraOn && (
                    <>
                      <video ref={videoRef} width="640" height="480" className="video-preview" />
                      <canvas ref={canvasRef} style={{ display: 'none' }} />
                      <Button onClick={captureImage} disabled={isCapturing} className="capture-button">
                        {isCapturing ? '正在捕捉...' : '捕捉人脸'}
                      </Button>
                    </>
                  )}
                </div>
                <div>
                  <Button onClick={handleFaceLogin} className="login-button">
                    登录
                  </Button>
                </div>
                <div>
                  <Button onClick={() => {
                    setShowRegisterForm(true);
                    setShowLoginSection(false);
                  }} className="register-button">
                    注册
                  </Button>
                </div>

              </div>
            )}
          </div>
        )}


        {showRegisterForm && (
          // 注册表单部分
          <div className="register-form">
            <h1 className="register-title">注册</h1>
            {/* <div className="login-methods">

          </div> */}
            {registerMethod === 'username' && (
              <div className="login-form">
                <Input
                  placeholder="用户名"
                  value={username}
                  onChange={(e) => setUsername(e)}
                  className="login-input"
                />
                <div className="password-input-container">
                  <Input
                    placeholder="密码"
                    type={passwordVisible ? 'text' : 'password'}
                    value={password}
                    onChange={(e) => setPassword(e)}
                    className="login-input"
                  />
                  <div className="password-eye-icon">
                    {passwordVisible ? (
                      <EyeOutline onClick={() => setPasswordVisible(false)} className="text-gray-500 cursor-pointer" />
                    ) : (
                      <EyeInvisibleOutline onClick={() => setPasswordVisible(true)} className="text-gray-500 cursor-pointer" />
                    )}
                  </div>
                </div>
                <Input
                  placeholder="手机号"
                  value={phoneNumber}
                  onChange={(e) => setPhoneNumber(e)}
                  className="login-input"
                />
                <div>
                  {!isCameraOn && (
                    <Button onClick={() => setIsCameraOn(true)} className="open-camera-button">
                      打开摄像头
                    </Button>
                  )}
                  {isCameraOn && (
                    <>
                      <video ref={videoRef} width="640" height="480" className="video-preview" />
                      <canvas ref={canvasRef} style={{ display: 'none' }} />
                      <Button onClick={captureImage} disabled={isCapturing} className="capture-button">
                        {isCapturing ? '正在捕捉...' : '捕捉人脸'}
                      </Button>
                    </>
                  )}
                </div>
                <div>
                  <Button onClick={() => {
                    setShowRegisterForm(false);
                    setShowLoginSection(true);
                  }} className="v-button">
                    取消
                  </Button>
                  <Button onClick={() => { handleRegister() }} className="v-button">
                    注册
                  </Button>
                </div>

              </div>
            )}
          </div>
        )}
      </div>
      {/* 右边的部分 */}
      <div className='footer'>
        <h1 className="footer-title">欢迎来到</h1>
        <h1>Maijia卖家管理后台</h1>
        <p>Maijia是一家专注于服装、鞋包、箱包、珠宝、家居、母婴、美妆、数码产品等全领域的综合性电商平台。</p>
      </div>
    </div>

  );
};

export default Login;